package driver

import (
	"fmt"
	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/credentials"
	"github.com/aws/aws-sdk-go/aws/session"
	"github.com/aws/aws-sdk-go/service/s3"
	"github.com/gin-gonic/gin"
	"img/common/response"
	"img/common/utils"
	"img/global"
	"io"
	"os"
	"path/filepath"
	"time"
)

const (
	uploadDirectory = "etc/"
)

func S3HandleUpload(c *gin.Context) {

	file, err := c.FormFile("file")

	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	// 为上传的文件生成唯一的文件名
	fileName := utils.GenerateFileName(file.Filename)
	filePath := filepath.Join(uploadDirectory, fileName)
	// 在服务器上创建一个文件以存储上传的内容
	f, err := os.Create(filePath)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	defer func() {
		f.Close()
		if err = os.Remove(filePath); err != nil {
			response.FailWithMessage(err.Error(), c)
			return
		}
	}()
	src, _ := file.Open()
	defer src.Close()
	// 将上传文件的内容从上传文件复制到服务器文件
	_, err = io.Copy(f, src)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	// 将文件上传到 AWS S3
	url, err := uploadToS3(fileName)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	contentType, err := utils.GetContentTypeByExtension(fileName)
	extension := filepath.Ext(fileName)
	res := map[string]interface{}{}
	res["filename"] = fileName
	res["originFileName"] = file.Filename
	res["contentType"] = contentType
	res["extension"] = extension
	res["size"] = file.Size
	res["path"] = "/" + global.S3_CREATED_DIR + fileName
	res["url"] = url
	response.OkWithData(res, c)
}

func uploadToS3(fileName string) (url string, err error) {
	sess, err := session.NewSession(&aws.Config{
		Region:      aws.String(global.IMG_CONFIG.App.Aws3.AwsRegion),
		Credentials: credentials.NewStaticCredentials(global.IMG_CONFIG.App.Aws3.AwsAccessKey, global.IMG_CONFIG.App.Aws3.AwsSecretKey, ""),
	})
	if err != nil {
		return "", err
	}
	filePath := filepath.Join(uploadDirectory, fileName)

	// 打开要上传的文件
	file, err := os.Open(filePath)
	defer file.Close()
	if err != nil {
		return "", err
	}

	// 创建 S3 会话
	svc := s3.New(sess)
	contentType, err := utils.GetContentTypeByExtension(fileName)
	if err != nil {
		return "", err
	}
	// 定义要创建的目录名称和存储桶名称
	directoryName := "upload/" + time.Now().Format("20060102") + "/"
	if directoryName != global.S3_CREATED_DIR {
		// 创建目录
		_, err = svc.PutObject(&s3.PutObjectInput{
			Bucket: aws.String(global.IMG_CONFIG.App.Aws3.S3Bucket),
			Key:    aws.String(directoryName),
			ACL:    aws.String("public-read"), // Set ACL to public-read
		})
		if err != nil {
			fmt.Println("Failed to create directory:", err)
			return "", err
		}
		global.S3_CREATED_DIR = directoryName
	}

	path := directoryName + fileName
	// 将文件上传到 S3
	_, err = svc.PutObject(&s3.PutObjectInput{
		Bucket:      aws.String(global.IMG_CONFIG.App.Aws3.S3Bucket),
		Key:         aws.String(path),
		Body:        file,
		ContentType: aws.String(contentType),
		ACL:         aws.String("public-read"), // Set ACL to public-read

	})
	if err != nil {
		return "", err
	}
	url = global.IMG_CONFIG.App.Aws3.Host + "/" + path
	return url, nil
}
